(function ($) {
    $.fn.idleTimeout = function (options) {
        // #Testing
        ////var defaults = {
        ////    inactivity: 2000, // 2 Seconds
        ////    noconfirm: 2000, //2 Seconds
        ////    sessionAlive: 2000, //2 Minutes
        ////redirect_url: './index.html#home',
        ////click_reset: true,
        ////alive_url: './index.html#home',
        ////logout_url: './index.html#home'
        ////}
        
        // #Release
        var defaults = {
            inactivity: 1800000, //30 Minutes
            noconfirm: 10000, //10 Seconds
            sessionAlive: 600000, //10 Minutes
            redirect_url: './index.html#home',
            click_reset: true,
            alive_url: './index.html#home',
            logout_url: './index.html#home'
        }

        var opts = $.extend(defaults, options);
        var liveTimeout, confTimeout, sessionTimeout;

       
        var start_liveTimeout = function () {
            clearTimeout(liveTimeout);
            clearTimeout(confTimeout);
            liveTimeout = setTimeout(logout, opts.inactivity);

            if (opts.sessionAlive) {
                clearTimeout(sessionTimeout);
                sessionTimeout = setTimeout(keep_session, opts.sessionAlive);
            }
        }

        var logout = function () {
            var my_dialog;
            var buttonsOpts = {};

            confTimeout = setTimeout(redirect, opts.noconfirm);

            buttonsOpts[opts.dialogButton] = function () {
                my_dialog.dialog('close');
                stay_logged_in();
            }
        }

        var redirect = function () {
            if (opts.logout_url) {
                $.get(opts.logout_url);
            }
            window.location.href = opts.redirect_url;
        }

        var stay_logged_in = function (el) {
            start_liveTimeout();
            if (opts.alive_url) {
                $.get(opts.alive_url);
            }
        }

        var keep_session = function () {
            $.get(opts.alive_url);
            clearTimeout(sessionTimeout);
            sessionTimeout = setTimeout(keep_session, opts.sessionAlive);
        }

        return this.each(function () {
            obj = $(this);
            start_liveTimeout();
            if (opts.click_reset) {
                $(document).bind('click', start_liveTimeout);
            }
            if (opts.sessionAlive) {
                keep_session();
            }
        });

    };
})(jQuery);